﻿using System;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Xc.DataAccess.Core;

namespace Xc.DataAccess.HyperTerminalCore.Models
{
    /// <summary>
    /// UDP客户端信息
    /// </summary>
    public class UdpClientInfo : ClientInfo<UdpClientInfo>, IUdpClientInfo
    {
        /// <summary>
        /// UDP客户端信息
        /// </summary>
        /// <param name="udpClient"></param>
        public UdpClientInfo(UdpClient udpClient,Encoding encoding):base(encoding)
        {
            UdpClient = udpClient;
            base.SetIpAddress(udpClient.Client);
        }
        public override void Close()
        {
            base.Close();
            RaisedClose(this);
            UdpClient?.Close();
        }
        /// <summary>
        /// 发送字节码数据
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override async Task<Result> Send(byte[] buffer)
        {
            if (buffer == null || buffer.Length == 0)
            {
                return Result.Reject("输入数据无效，无法发送");
            }

            try
            {

                var length = await UdpClient.SendAsync(buffer, buffer.Length);
                SendCount += length;
                return Result.Accept("发送成功");
            }
            catch (Exception err)
            {

                return Result.Reject(err.Message);

            }

        }



        /// <summary>
        /// TCP客户端
        /// </summary>
        public UdpClient UdpClient { get; private set; }


        /// <summary>
        /// 接收数据
        /// </summary>
        protected override async void ReceiveData()
        {
            await Task.Run(async () =>
            {
                Token.Cancel();
                await Task.Delay(100);
                Token = new CancellationTokenSource();
                while (!Token.IsCancellationRequested)
                {
                    try
                    {

                        byte[] buffer = new byte[40906];
                        var receive = await UdpClient.ReceiveAsync();
                        if (receive.Buffer.Length > 0)
                        {
                            IpAddress = receive.RemoteEndPoint?.ToString();
                            ReceiveCount += receive.Buffer.Length;
                            if (UseReceive == false)
                            {
                                receiveBuffer.Enqueue(receive.Buffer);
                            }
                            else
                            {
                                RaisedReceiveMessage(receive.Buffer, this);
                            }
                        }
                        else
                        {
                            Close();
                            break;
                        }
                        await Task.Delay(5);
                    }
                    catch (Exception err)
                    {
                        Close();
                        break;
                    }

                }
            });

        }




    }
}
